import Card from '@/components/Card';
import {
  monitorServerControllerFindAllStationUsers,
  monitorServerControllerMonitorRule,
  monitorServerControllerSaveComponent,
  monitorServerControllerSaveDatabase,
  monitorServerControllerSaveHard,
  monitorServerControllerSaveRule,
} from '@/services/ess/alertConfig';
import type { ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Col, Flex, Form, Input, message, Row, Select, Spin, Switch } from 'antd';
import { parse } from 'querystring';
import React, { useEffect, useMemo, useState } from 'react';
import { useIntl, useLocation, useRequest } from 'umi';
import styles from '../index.less';

const { Option } = Select;

interface AlarmConfigProps {
  id: string;
}

const AlarmConfig: React.FC<AlarmConfigProps> = () => {
  const intl = useIntl();
  const location = useLocation();
  const { stationid } = parse(location.search.slice(1)) as { stationid: string };

  const {
    data: monitorRuleData,
    loading,
    refresh,
  } = useRequest(() => monitorServerControllerMonitorRule({ stationId: parseInt(stationid) }));

  const { data: userListData, loading: userLoading } = useRequest(() =>
    monitorServerControllerFindAllStationUsers({ stationId: parseInt(stationid) }),
  );

  const hardwareResourceData = [
    {
      name: intl.formatMessage({ id: 'alarmConfig.hardwareResource.cpuUsage' }),
      placeholder: intl.formatMessage({ id: 'alarmConfig.hardwareResource.cpuUsage' }),
      value: monitorRuleData?.server?.cpuRate ?? 0,
      unit: '%',
    },
    {
      name: intl.formatMessage({ id: 'alarmConfig.hardwareResource.cpuTemperature' }),
      placeholder: intl.formatMessage({ id: 'alarmConfig.hardwareResource.cpuTemperature' }),
      value: monitorRuleData?.server?.cpuTemp ?? 0,
      unit: '°C',
    },
    {
      name: intl.formatMessage({ id: 'alarmConfig.hardwareResource.memoryUsage' }),
      placeholder: intl.formatMessage({ id: 'alarmConfig.hardwareResource.memoryUsage' }),
      value: monitorRuleData?.server?.memoryRate ?? 0,
      unit: '%',
    },
    {
      name: intl.formatMessage({ id: 'alarmConfig.hardwareResource.diskUsage' }),
      placeholder: intl.formatMessage({ id: 'alarmConfig.hardwareResource.diskUsage' }),
      value: monitorRuleData?.server?.diskRate ?? 0,
      unit: '%',
    },
  ];

  const [databaseResourceData, setDatabaseResourceData] = useState<any[]>([]);

  useEffect(() => {
    if (monitorRuleData?.databaseList) {
      const formattedData = monitorRuleData.databaseList.map((db) => ({
        name: intl.formatMessage({
          id: `alarmConfig.databaseResource.${db.databaseName?.toLowerCase() ?? ''}`,
        }),
        status: Number(db.enableAlert) === 1 ? 'on' : 'off',
        databaseType: db.databaseType,
        databaseName: db.databaseName,
      }));
      setDatabaseResourceData(formattedData);
    }
  }, [monitorRuleData, intl]);

  const componentResourceData = useMemo(() => {
    if (monitorRuleData?.componentList) {
      return monitorRuleData.componentList.map((component) => ({
        no: component.componentId,
        name: component.componentName,
        alarmStatus: Number(component.enableAlert) === 1 ? 'on' : 'off',
        componentId: component.componentId,
      }));
    }
    return [];
  }, [monitorRuleData]);

  const handleComponentStatusChange = async (
    componentId: string,
    componentName: string,
    checked: boolean,
  ) => {
    try {
      const payload = {
        stationId: parseInt(stationid),
        componentId: componentId,
        componentName: componentName,
        enableAlert: checked ? '1' : '0',
      };

      const response = await monitorServerControllerSaveComponent(payload);
      if (response.success) {
        message.success(intl.formatMessage({ id: 'alarmConfig.message.saveSuccess' }));
        // 刷新数据
        refresh();
      } else {
        message.error(intl.formatMessage({ id: 'alarmConfig.message.saveFailed' }));
      }
    } catch (error) {
      console.error('Save component status failed:', error);
      message.error(intl.formatMessage({ id: 'alarmConfig.message.saveFailed' }));
    }
  };

  const componentResourceColumns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'alarmConfig.componentResource.no' }),
      dataIndex: 'no',
      key: 'no',
    },
    {
      title: intl.formatMessage({ id: 'alarmConfig.componentResource.name' }),
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: intl.formatMessage({ id: 'alarmConfig.componentResource.alarmStatus' }),
      dataIndex: 'alarmStatus',
      key: 'alarmStatus',
      render: (_, record) => (
        <Switch
          size="small"
          checked={record.alarmStatus === 'on'}
          checkedChildren={intl.formatMessage({ id: 'alarmConfig.switch.enable' })}
          unCheckedChildren={intl.formatMessage({ id: 'alarmConfig.switch.disable' })}
          onChange={(checked) =>
            handleComponentStatusChange(record.componentId, record.name, checked)
          }
        />
      ),
    },
  ];

  const [form] = Form.useForm();
  const [hardwareForm] = Form.useForm();

  // Add this effect to set initial form values when data is loaded
  useEffect(() => {
    if (monitorRuleData?.rule) {
      form.setFieldsValue({
        hardTimePeriod: monitorRuleData.rule.hardTimePeriod,
        hardAlertNum: monitorRuleData.rule.hardAlertNum,
        softTimePeriod: monitorRuleData.rule.softTimePeriod,
        softAlertNum: monitorRuleData.rule.softAlertNum,
        alarmUser: monitorRuleData.rule.userList?.map((user) => user.userId) || [],
      });
    }
  }, [monitorRuleData, form]);

  // Add this effect to set initial form values when data is loaded
  useEffect(() => {
    if (monitorRuleData?.server) {
      hardwareForm.setFieldsValue({
        hardware_0: monitorRuleData.server.cpuRate,
        hardware_1: monitorRuleData.server.cpuTemp,
        hardware_2: monitorRuleData.server.memoryRate,
        hardware_3: monitorRuleData.server.diskRate,
      });
    }
  }, [monitorRuleData, hardwareForm]);

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      const payload = {
        stationId: parseInt(stationid),
        hardTimePeriod: parseInt(values.hardTimePeriod),
        hardAlertNum: parseInt(values.hardAlertNum),
        softTimePeriod: parseInt(values.softTimePeriod),
        softAlertNum: parseInt(values.softAlertNum),
        userIds: values.alarmUser,
      };

      const response = await monitorServerControllerSaveRule(payload);
      if (response.success) {
        message.success(intl.formatMessage({ id: 'alarmConfig.message.saveSuccess' }));
      } else {
        message.error(intl.formatMessage({ id: 'alarmConfig.message.saveFailed' }));
      }
    } catch (error) {
      console.error('Save failed:', error);
      message.error(intl.formatMessage({ id: 'alarmConfig.message.saveFailed' }));
    }
  };

  const handleSaveHardware = async () => {
    try {
      const values = await hardwareForm.validateFields();
      const payload = {
        stationId: parseInt(stationid),
        cpuRate: parseInt(values.hardware_0),
        cpuTemp: parseInt(values.hardware_1),
        memoryRate: parseInt(values.hardware_2),
        diskRate: parseInt(values.hardware_3),
      };

      const response = await monitorServerControllerSaveHard(payload);
      if (response.success) {
        message.success(intl.formatMessage({ id: 'alarmConfig.message.saveSuccess' }));
      } else {
        message.error(intl.formatMessage({ id: 'alarmConfig.message.saveFailed' }));
      }
    } catch (error) {
      console.error('Save hardware settings failed:', error);
      message.error(intl.formatMessage({ id: 'alarmConfig.message.saveFailed' }));
    }
  };

  const handleDatabaseStatusChange = async (
    databaseType: number,
    databaseName: string,
    checked: boolean,
  ) => {
    try {
      const payload = {
        stationId: parseInt(stationid),
        databaseType: databaseType,
        databaseName: databaseName,
        enableAlert: checked ? 1 : 0,
      };

      const response = await monitorServerControllerSaveDatabase(payload);
      if (response.success) {
        message.success(intl.formatMessage({ id: 'alarmConfig.message.saveSuccess' }));
        // Update local state to reflect the change
        setDatabaseResourceData((prevData) =>
          prevData.map((item) =>
            item.databaseType === databaseType ? { ...item, status: checked ? 'on' : 'off' } : item,
          ),
        );
      } else {
        message.error(intl.formatMessage({ id: 'alarmConfig.message.saveFailed' }));
      }
    } catch (error) {
      console.error('Save database status failed:', error);
      message.error(intl.formatMessage({ id: 'alarmConfig.message.saveFailed' }));
    }
  };

  return (
    <Spin spinning={loading}>
      <div className={styles.alarmConfigContainer}>
        <Card bordered={false}>
          <Form form={form} layout="inline" className={styles.filterForm}>
            <Flex wrap="nowrap" gap="0">
              <Form.Item
                name="hardTimePeriod"
                label={intl.formatMessage({ id: 'alarmConfig.filter.hardwareResource' })}
              >
                <Input
                  type="number"
                  min={1}
                  style={{ width: 100 }}
                  onKeyPress={(event) => {
                    if (!/[0-9]/.test(event.key)) {
                      event.preventDefault();
                    }
                  }}
                  onChange={(e) => {
                    const value = e.target.value;
                    if (value === '0') {
                      e.target.value = '';
                    } else {
                      e.target.value = value.replace(/\D/g, '');
                    }
                  }}
                />
              </Form.Item>
              <Form.Item
                name="hardAlertNum"
                label={intl.formatMessage({ id: 'alarmConfig.filter.triggerInterval' })}
              >
                <Input
                  type="number"
                  min={0}
                  style={{ width: 100 }}
                  onKeyPress={(event) => {
                    if (!/[0-9]/.test(event.key)) {
                      event.preventDefault();
                    }
                  }}
                />
              </Form.Item>
              <Form.Item>
                <span>{intl.formatMessage({ id: 'alarmConfig.filter.triggerTimes' })}</span>
                <span>{intl.formatMessage({ id: 'alarmConfig.filter.triggerAlarm' })}</span>
              </Form.Item>
            </Flex>
            <Flex wrap="nowrap" gap="0" style={{ marginTop: '16px' }}>
              <Form.Item
                name="softTimePeriod"
                label={intl.formatMessage({ id: 'alarmConfig.filter.sofeStuff' })}
              >
                <Input
                  type="number"
                  min={1}
                  style={{ width: 100 }}
                  onKeyPress={(event) => {
                    if (!/[0-9]/.test(event.key)) {
                      event.preventDefault();
                    }
                  }}
                  onChange={(e) => {
                    const value = e.target.value;
                    if (value === '0') {
                      e.target.value = '';
                    } else {
                      e.target.value = value.replace(/\D/g, '');
                    }
                  }}
                />
              </Form.Item>
              <Form.Item
                name="softAlertNum"
                label={intl.formatMessage({ id: 'alarmConfig.filter.triggerInterval' })}
              >
                <Input
                  type="number"
                  min={0}
                  style={{ width: 100 }}
                  onKeyPress={(event) => {
                    if (!/[0-9]/.test(event.key)) {
                      event.preventDefault();
                    }
                  }}
                />
              </Form.Item>
              <Form.Item>
                <span>{intl.formatMessage({ id: 'alarmConfig.filter.triggerTimes' })}</span>
                <span>{intl.formatMessage({ id: 'alarmConfig.filter.triggerAlarm' })}</span>
              </Form.Item>
            </Flex>
            <Flex wrap="nowrap" gap="0" style={{ marginTop: '16px' }}>
              <Form.Item
                name="alarmUser"
                label={intl.formatMessage({ id: 'alarmConfig.filter.alarmUser' })}
              >
                <Select
                  mode="multiple"
                  style={{ width: 400 }}
                  loading={userLoading}
                  placeholder={intl.formatMessage({ id: 'alarmConfig.filter.selectUsers' })}
                >
                  {userListData?.map((user: API.MonitorUserDTO) => (
                    <Option key={user.userId} value={user.userId}>
                      {user.userName}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Flex>
            <Form.Item style={{ marginTop: '16px' }}>
              <Button type="primary" onClick={handleSave}>
                {intl.formatMessage({ id: 'alarmConfig.button.save' })}
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={() => form.resetFields()}>
                {intl.formatMessage({ id: 'alarmConfig.button.reset' })}
              </Button>
            </Form.Item>
          </Form>
        </Card>
        <div className={styles.detailContainerCardBound}></div>
        <Card
          title={intl.formatMessage({ id: 'alarmConfig.hardwareResource.title' })}
          style={{ marginTop: 16 }}
          bordered={false}
        >
          <Form form={hardwareForm} layout="horizontal">
            <Row gutter={16}>
              {hardwareResourceData.map((item, index) => (
                <Col span={6} key={index}>
                  <Form.Item name={`hardware_${index}`} label={item.name}>
                    <Input placeholder={item.placeholder} addonAfter={item.unit} />
                  </Form.Item>
                </Col>
              ))}
            </Row>
            <Form.Item>
              <Button type="primary" onClick={handleSaveHardware}>
                {intl.formatMessage({ id: 'alarmConfig.button.save' })}
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={() => hardwareForm.resetFields()}>
                {intl.formatMessage({ id: 'alarmConfig.button.reset' })}
              </Button>
            </Form.Item>
          </Form>
        </Card>
        <div className={styles.detailContainerCardBound}></div>
        <Card
          title={intl.formatMessage({ id: 'alarmConfig.databaseResource.title' })}
          style={{ marginTop: 16 }}
          bordered={false}
        >
          <Flex wrap="nowrap" gap="small">
            {databaseResourceData.map((item, index) => (
              <Flex key={index} align="center" style={{ width: '30%' }} gap={'small'}>
                <span>{item.name}</span>
                <Switch
                  checked={item.status === 'on'}
                  size="small"
                  checkedChildren={intl.formatMessage({ id: 'alarmConfig.switch.enable' })}
                  unCheckedChildren={intl.formatMessage({ id: 'alarmConfig.switch.disable' })}
                  onChange={(checked) => {
                    handleDatabaseStatusChange(item.databaseType, item.databaseName, checked);
                  }}
                />
              </Flex>
            ))}
          </Flex>
        </Card>
        <div className={styles.detailContainerCardBound}></div>
        <Card
          title={intl.formatMessage({ id: 'alarmConfig.componentResource.title' })}
          style={{ marginTop: 16 }}
          bordered={false}
        >
          <ProTable
            columns={componentResourceColumns}
            dataSource={componentResourceData}
            pagination={{
              showSizeChanger: true,
              defaultPageSize: 10,
            }}
            search={false}
            toolBarRender={false}
            rowKey="componentId"
          />
        </Card>
      </div>
    </Spin>
  );
};

export default AlarmConfig;
